# Created by Gao Song on 2019-04-16

from time import sleep
from datetime import datetime

from core import pid

import logging
logger = logging.getLogger('scheduler')


class BaseScheduler:

    def __init__(self):
        self.SCHEDULER_INTERVAL = 5
        self.HEARTBEAT_INTERVAL = 20

        self.status = None
        self._exit = False

        self.scheduler_type = None
        self.scheduler_name = None

    def start(self):
        pid.save_pid(self.scheduler_type, self.scheduler_name)
        count = 0
        logger.info(f'start...interval: {self.SCHEDULER_INTERVAL}, hb_interval: {self.HEARTBEAT_INTERVAL}')
        while not self._exit:
            count += self.SCHEDULER_INTERVAL
            ts = datetime.now()
            if count > self.HEARTBEAT_INTERVAL:
                self.heartbeat(ts)
                count = 0
            self.process(ts)
            sleep(self.SCHEDULER_INTERVAL)

    def stop(self):
        logger.info('stop')
        self._exit = True

    def heartbeat(self, ts):
        pass

    def process(self, ts):
        pass


